import { createRouter, createWebHistory } from "vue-router";
import store from "../store"

export const routes = [
  {
    path: "/login",
    name: "login",
    label: "登录",
    hidden: true,//不参与菜单栏显示
    component: () => import("../views/login/index.vue"),
  },
  {
    path: "/403",
    name: "no-permission",
    label: "403",
    hidden: true,//不参与菜单栏显示
    component: () => import("../views/error/no-permission.vue"),
  },
  {
    path: "/",
    name: "home",
    label: "首页",
    component: () => import("../views/layout/index.vue"),
  },
  {
    path: "/banner",
    name: "banner",
    label: "轮播图管理",
    component: () => import("../views/layout/index.vue"),
    children: [
      {
        path: "list",
        name: "banner-list",
        label: "轮播图列表",
        component: () => import("@/views/banner/list.vue"),
      },
      {
        path: "add",
        name: "banner-add",
        label: "轮播图新增",
        component: () => import("@/views/banner/add.vue"),
      },
    ],
  },

  {
    path: "/manager",
    name: "manager",
    label: "管理员管理",
    component: () => import("../views/layout/index.vue"),
    children: [
      {
        path: "list",
        name: "manager-list",
        label: "管理员列表",
        component: () => import("../views/manager/list.vue"),
      },

    ],
  },
  {
    path: "/goods",
    name: "goods",
    label: "商品管理",
    component: () => import("../views/layout/index.vue"),
    children: [
      {
        path: "list",
        name: "goods-list",
        label: "商品列表",
        component: () => import("../views/goods/list.vue"),
      },

    ],
  },
];




const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
});
const whileList = ["login", "no-permission"]
router.beforeEach((to, from, next) => {
  const name = to.name
  if (whileList.includes(name)) {
    next()
  } else {
    const token = localStorage.getItem("token");
    if (token) {
      //登陆了在判断要去的页面是否有权限
      //next()
      if (store.state.role === 2) {
        next()
      } else {
        if (store.state.pageRoles.includes(name)) {
          next()
        } else {
          //没有权限
          next({ name: "no-permission" });
        }
      }

    } else {
      next({ name: "login" });
    }
  }
});

export default router;
